<?php

require_once 'Pipes/Controller.php';
require_once 'Pipes/Model/Mapper/Factory.php';
require_once 'PipesImpl/Model/Mapper.php';

class Pipes_Controller_Model extends Pipes_Controller
{
    protected $modelMapper = null;
    protected $model = null;
    protected $modelList = null;
    
    public function __construct(PipesImpl_Config $config)
    {
        parent::__construct($config);
        
        $this->config = $config;
        $factory = new Pipes_Model_Mapper_Factory($this->config);
        $this->modelMapper = $factory->factory($this->name);
    }
    
    protected function _newFilter() {
        return new Pipes_Filter();
    }

    protected function actionAdd()
    {
        $this->actionEdit(null);
    }
    
    protected function actionEdit($id)
    {
        $idKey = $this->name . '_id';
        $this->view->model = $this->modelMapper->find($this->_newFilter()->$idKey->equals($id));
    }
    
    protected function actionView($id) 
    {
        $this->view->model = $this->modelMapper->find($id);
    }
    
    protected function actionBrowse()
    {
        $this->modelList = $this->modelMapper->findAll();
        $this->view->modelList = $this->modelList;
    }

    protected function actionRemove($id) {
        $model = $this->modelMapper->find($id);
        $this->modelMapper->remove($model);

        $this->view->model = $model;
    }
    
    protected function dispatch()
    {
        $name = strtolower($this->name);
        if (isset($_POST['pipes']['action'][$name])) {
            if (isset($_POST[$name]["{$name}_id"])) {
                $this->model = $this->modelMapper->find($_POST[$name]["{$name}_id"]);
                unset($_POST[$name]["{$name}_id"]);
            } else {
                $this->model = $this->modelMapper->find();
            }
            foreach ($_POST[$name] as $key => $value) {
                $this->model->$key = $value;
            }
            
            $action = strtolower($_POST['pipes']['action'][$name]);
            $this->model->$action();
        }

        parent::dispatch();
    }
}

